

from rest_framework import serializers
from users.models import User

class UserModelSerializer(serializers.ModelSerializer):

    class Meta:
        model = User
        fields = [
            'id', # 默认只参与序列化器
            'username',
            'mobile',
            'email',

            'password' # 反序列化校验密码，只参与反序列化 —— 把password的约束条件write_only=True
        ]

        extra_kwargs = {
            'password': {'write_only': True, 'max_length': 20},
            'username': {'max_length': 20}
        }

    def create(self, validated_data):
        # 重写create函数，使用create_user新建用户对象，密码加密
        # validated_data = {"username": "weiwei"}
        return User.objects.create_user(**validated_data) # create_user(**{"username": "weiwei"}) --> create_user(username="weiwei")
